package com.andaily.service.impl;

import com.andaily.domain.dto.user.UserDto;
import com.andaily.domain.dto.user.UserListDto;
import com.andaily.domain.shared.paginated.PaginatedLoader;
import com.andaily.domain.shared.security.AndailyUserDetails;
import com.andaily.domain.user.User;
import com.andaily.domain.user.UserRepository;
import com.andaily.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author Shengzhao Li
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("Not found any user for username[" + username + "]");
        }
        return new AndailyUserDetails(user);
    }

    @Override
    public UserDto loadUserDto(String guid) {
        if (guid == null) {
            return null;
        }
        final User user = userRepository.findByGuid(guid, User.class);
        return user == null ? null : new UserDto(user);
    }


    @Override
    public UserListDto loadUserListDto(UserListDto listDto) {
        final Map<String, Object> map = listDto.queryMap();
        return listDto.load(new PaginatedLoader<UserDto>() {
            @Override
            public List<UserDto> loadList() {
                List<User> users = userRepository.findListUsers(map);
                return UserDto.toDtos(users);
            }

            @Override
            public int loadTotalSize() {
                return userRepository.totalListUsers(map);
            }
        });
    }
}